package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @description: 课程分类相关实现类
 * @author: ajie
 * @date: 2024/1/11 21:15:52
 * @version: 1.0
 */
@Service
@Slf4j
public class CourseCategoryServiceImpl implements CourseCategoryService {

    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    /**
     * description: 课程分类树形结构查询
     * @param id
     * @return:
     * @author: ajie
     * @date: 2024/1/11 21:20
     */
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //调用mapper递归查询出分类对象
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);

        //找到每个结点的子结点，最终封装成List<CourseCategoryTreeDto>
        //先将List转成map，key就是结点的id，value就是CourseCategoryTreeDto对象，
        //目的就是为了方便从map获取结点, filter(item->!id.equals(item.getId()))把根节点排除
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream()
                .filter(item->!id.equals(item.getId()))
                .collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //定义一个list作为最终返回的的list
        List<CourseCategoryTreeDto> courseCategoryList = new ArrayList<>();
        //从头遍历List<CourseCategoryTreeDto>，一边遍历一边找子结点放在父节点的childrenTreeNodes
        courseCategoryTreeDtos.stream().filter(item->!id.equals(item.getId())).forEach(item -> {
            if (item.getParentid().equals(id)){
                courseCategoryList.add(item);
            }
            //找到结点的父节点
            CourseCategoryTreeDto courseCategoryTreeParent = mapTemp.get(item.getParentid());
            if (courseCategoryTreeParent != null){
                if(courseCategoryTreeParent.getChildrenTreeNodes()==null){
                    //如果该父节点的ChildrenTreeNodes属性为空要new一个集合，因为要向该集合中放它的的子结点
                    courseCategoryTreeParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                //到每个结点的子结点放在父节点的ChildrenTreeNodes属性中
                courseCategoryTreeParent.getChildrenTreeNodes().add(item);

            }
        });


        return courseCategoryList;
    }
}
